package com.example.exam;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class MainActivity extends AppCompatActivity {

    private Context mContext;
    private GridView grid_photo;
    private BaseAdapter mAdapter = null;
    private ArrayList<Icon> mData = null;
    private MyDatabaseHelper dbHelper;
    String token;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        Intent intent = getIntent();
        token = intent.getStringExtra("token_data");

        sendRequestWithOkHttp();

        dbHelper = new MyDatabaseHelper(this, "Question.db", null, 1);
        dbHelper.getWritableDatabase();

        mContext = MainActivity.this;
        grid_photo = (GridView) findViewById(R.id.grid_photo);

        mData = new ArrayList<Icon>();
        mData.add(new Icon(R.mipmap.iv_icon_2, "开始考试"));
        mData.add(new Icon(R.mipmap.iv_icon_3, "更新题库"));
        mData.add(new Icon(R.drawable.lv_4, "版本更新"));
        mData.add(new Icon(R.mipmap.iv_icon_1, "待开发"));
        mData.add(new Icon(R.mipmap.iv_icon_4, "退出"));

        mAdapter = new MyAdapter<Icon>(mData, R.layout.item_grid_icon) {
            @Override
            public void bindView(ViewHolder holder, Icon obj) {
                holder.setImageResource(R.id.img_icon, obj.getiId());
                holder.setText(R.id.txt_icon, obj.getiName());
            }
        };

        grid_photo.setAdapter(mAdapter);

        grid_photo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position){
                    case 0:
                        update();
                        if(Questions.QuestionsList.size() == 0){
                            Toast.makeText(mContext, "请下载题目后再开始做题", Toast.LENGTH_SHORT).show();
                            break;
                        }
                        update();
                        addExam();
                        break;
                    case 1:
                        sendRequestWithOkHttp();
                        Toast.makeText(mContext, "更新成功", Toast.LENGTH_SHORT).show();
                        break;
                    case 2:
                        Toast.makeText(mContext, "此功能待开发", Toast.LENGTH_SHORT).show();
                        break;
                    case 3:
                        Toast.makeText(mContext, "此功能待开发", Toast.LENGTH_SHORT).show();
                        break;
                    case 4:
                        save("no");
                        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                        startActivity(intent);
                        Toast.makeText(mContext, "账号已退出", Toast.LENGTH_SHORT).show();
                        finish();
                        break;
                }
            }
        });

    }

    public void addExam(){
        Intent intent = new Intent(this, ExamActivity.class);
        intent.putExtra("ExamId", "0");
        startActivity(intent);
    }

    void update(){
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        //查询Book表中所有数据
        Cursor cursor = db.query("Que", null, null, null, null, null, null);
        Questions questions;
        if(cursor.moveToFirst()){
            do{
                //遍历Cursor对象， 取出数据并打印
                String id = cursor.getString(cursor.getColumnIndex("id"));
                String lesson = cursor.getString(cursor.getColumnIndex("lesson"));
                String chapter = cursor.getString(cursor.getColumnIndex("chapter"));
                String difficulty = cursor.getString(cursor.getColumnIndex("difficulty"));
                String title = cursor.getString(cursor.getColumnIndex("title"));
                String option_a = cursor.getString(cursor.getColumnIndex("option_a"));
                String option_b = cursor.getString(cursor.getColumnIndex("option_b"));
                String option_c = cursor.getString(cursor.getColumnIndex("option_c"));
                String option_d = cursor.getString(cursor.getColumnIndex("option_d"));
                Questions.QuestionsList.add(new Questions(id, lesson, chapter, difficulty, title, option_a, option_b, option_c, option_d));
            }while (cursor.moveToNext());
        }
        cursor.close();
    }

    private void sendRequestWithOkHttp(){
        //开启新线程做耗时操作
        new Thread(new Runnable(){
            @Override
            public void run() {
                try{
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("http://exam.mujiayiling.com/api/singlechoicelistall.json")
                            .addHeader("token",token)
                            .build();//创建一个Request对象
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    parseJSONWithJSONObject(responseData);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    void parseJSONWithJSONObject(String jsonData){
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.delete("Que", "zdid > ?", new String[] {"0"});
        ContentValues values = new ContentValues();
        try {
            JSONObject jsonObject = new JSONObject(jsonData);
            JSONArray dataJSON = jsonObject.getJSONArray("data");
            for(int i = 0; i < dataJSON.length(); i++) {
                JSONObject jsonObject1 = (JSONObject) dataJSON.get(i);
                String id = jsonObject1.getString("singlechoice_id");
                String lesson = jsonObject1.getString("lesson_id");
                String chapter = jsonObject1.getString("chapter_id");
                String difficulty = jsonObject1.getString("difficulty");
                String title = jsonObject1.getString("title");
                String option_a = jsonObject1.getString("option_a");
                String option_b = jsonObject1.getString("option_b");
                String option_c = jsonObject1.getString("option_c");
                String option_d = jsonObject1.getString("option_d");
                values.put("id", id);
                values.put("lesson", lesson);
                values.put("chapter", chapter);
                values.put("difficulty", difficulty);
                values.put("title", title);
                values.put("option_a", option_a);
                values.put("option_b", option_b);
                values.put("option_c", option_c);
                values.put("option_d", option_d);
                db.insert("Que", null, values);
                values.clear();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    public void save(String inputText){
        FileOutputStream out = null;
        BufferedWriter writer = null;
        try{
            out = openFileOutput("token", Context.MODE_PRIVATE);
            writer = new BufferedWriter(new OutputStreamWriter(out));
            writer.write(inputText);
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try{
                if(writer != null){
                    writer.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

    public String load(){
        FileInputStream in = null;
        BufferedReader reader = null;
        StringBuilder content = new StringBuilder();
        try{
            in = openFileInput("token");
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while((line = reader.readLine()) != null){
                content.append(line);
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(reader != null){
                try{
                    reader.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
        return content.toString();
    }

}